// pages\profile\profile.js
const app = getApp();
const baseUrl = getApp().getApiBaseUrl();

Page({
  data: {
    userInfo: {
      avatar: '',
      name: '',
      gender: 0,
      province: '',
      mobile: ''
    },
    defaultAvatarUrl: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
    genderList: ['未设置', '男', '女'],
    genderIndex: 0,
    region: ['未设置', '', ''],
    isLoading: false,
    customToast: null // 初始化 customToast
  },

  onLoad() {
    // 立即尝试初始化 customToast
    this.initCustomToast();
    this.fetchUserInfo();
  },

  onReady() {
    // 延迟再次尝试初始化，确保组件加载
    setTimeout(() => {
      this.initCustomToast();
    }, 100);
  },

  initCustomToast() {
    const toast = this.selectComponent('#customToast');
    if (toast) {
      this.setData({ customToast: toast });
      console.log('customToast 初始化成功');
    } else {
      console.warn('customToast 组件未找到');
    }
  },

  showToast(options) {
    const toast = this.data.customToast;
    if (toast && typeof toast.showToast === 'function') {
      toast.showToast(options);
    } else {
      console.warn('customToast 未初始化，使用默认 wx.showToast');
      wx.showToast(options);
    }
  },

  onShow() {
    this.fetchUserInfo();
  },

  // 获取用户信息
  fetchUserInfo() {
    const openID = wx.getStorageSync('openID');
    const jwt_token = wx.getStorageSync('jwt_token');
    if (!openID || !jwt_token) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }

    this.setData({ isLoading: true });
    wx.request({
      url: `${baseUrl}/user/settings`,
      method: 'GET',
      data: { openID },
      header: { 'Authorization': `Bearer ${jwt_token}` },
      success: (res) => {
        if (res.statusCode === 200) {
          const { avatar, name, gender, province, mobile } = res.data; // 修改为 name
          const genderIndex = gender || 0;
          const region = province === '未设置' ? ['未设置', '', ''] : province.split(' ');
          this.setData({
            'userInfo.avatar': avatar || '',
            'userInfo.name': name || '未设置', // 修改为 name
            'userInfo.gender': genderIndex,
            'userInfo.province': province || '未设置',
            'userInfo.mobile': mobile || '',
            genderIndex,
            region
          });
        } else {
          wx.showToast({ title: res.data.detail || '获取用户信息失败', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('获取用户信息失败:', err);
        wx.showToast({ title: '网络错误', icon: 'none' });
      },
      complete: () => {
        this.setData({ isLoading: false });
      }
    });
  },

  updateUserInfo(field, value) {
    const openID = wx.getStorageSync('openID');
    const jwt_token = wx.getStorageSync('jwt_token');
    if (!openID || !jwt_token) {
      this.showToast({ title: '请先登录', icon: 'none', top: 200 });
      return;
    }

    const requestData = { openID, [field]: value };
    this.setData({ isLoading: true });
    wx.request({
      url: `${baseUrl}/user/wechat/info`,
      method: 'POST',
      data: requestData,
      header: { 'Authorization': `Bearer ${jwt_token}` },
      success: (res) => {
        if (res.statusCode === 200) {
          const updatedUserInfo = res.data;
          this.setData({
            'userInfo.avatar': updatedUserInfo.avatar || '',
            'userInfo.name': updatedUserInfo.name || '未设置', // 修改为 name
            'userInfo.gender': updatedUserInfo.gender || 0,
            'userInfo.province': updatedUserInfo.province || '未设置',
            'userInfo.mobile': updatedUserInfo.mobile || ''
          });
          this.showToast({ 
            title: `${field === 'name' ? '名字' : field === 'gender' ? '性别' : '地区'}更新成功`, // 修改为 name
            top: 200 
          });
        } else {
          this.showToast({ title: res.data.detail || '更新失败', icon: 'none', top: 200 });
        }
      },
      fail: (err) => {
        console.error(`更新${field}失败:`, err);
        this.showToast({ title: '网络错误', icon: 'none', top: 200 });
      },
      complete: () => {
        this.setData({ isLoading: false });
      }
    });
  },

  // 修改方法名为 onModifyName，并调整字段为 name
  onModifyName() {
    if (this.data.isLoading) return;

    wx.showModal({
      title: '修改名字',
      editable: true,
      placeholderText: '请输入名字（最多10个字符）',
      success: (res) => {
        if (res.confirm && res.content) {
          let name = res.content.trim(); // 修改为 name
          // 基本输入验证
          if (!name) {
            this.showToast({ title: '名字不能为空', icon: 'none', top: 200 });
            return;
          }
          
          // 字数限制
          if (name.length > 10) {
            this.showToast({ title: '名字不能超过10个字符', icon: 'none', top: 200 });
            return;
          }

          // 防SQL注入基本过滤（小程序端只做基础检查，后端需做更严格验证）
          const sqlInjectionPattern = /['";\-\-]/g;
          if (sqlInjectionPattern.test(name)) {
            this.showToast({ title: '名字包含非法字符', icon: 'none', top: 200 });
            return;
          }

          // 更新名字
          this.updateUserInfo('name', name); // 修改为 name
        }
      },
      fail: (err) => {
        console.error('弹窗失败:', err);
      }
    });
  },

  onChooseAvatar(e) {
    const { avatarUrl } = e.detail;
    if (!avatarUrl) {
      wx.showToast({ title: '头像选择失败', icon: 'none' });
      return;
    }

    const openID = wx.getStorageSync('openID');
    const jwt_token = wx.getStorageSync('jwt_token');
    if (!openID || !jwt_token) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }

    this.setData({ isLoading: true });
    wx.uploadFile({
      url: `${baseUrl}/user/upload-avatar`,
      filePath: avatarUrl,
      name: 'file',
      formData: { openID },
      header: { 'Authorization': `Bearer ${jwt_token}` },
      success: (res) => {
        const data = JSON.parse(res.data);
        if (res.statusCode === 200 && data.avatar) {
          this.setData({ 'userInfo.avatar': data.avatar });
          wx.showToast({ title: '头像更新成功' });
        } else {
          wx.showToast({ title: data.detail || '头像上传失败', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('头像上传失败:', err);
        wx.showToast({ title: '网络错误', icon: 'none' });
      },
      complete: () => {
        this.setData({ isLoading: false });
      }
    });
  },

  onGenderChange(e) {
    const genderIndex = parseInt(e.detail.value);
    this.updateUserInfo('gender', genderIndex);
  },

  onRegionChange(e) {
    const region = e.detail.value;
    const province = region[0] === '未设置' ? '未设置' : region.join(' ');
    this.updateUserInfo('province', province);
  },

  getPhoneNumber(e) {
    if (e.detail.errMsg !== 'getPhoneNumber:ok') {
      const errno = e.detail.errno;
      let title = '授权失败，请允许获取手机号';
      if (errno === 1400001) {
        title = '功能使用次数已达上限，请联系管理员';
      }
      this.showToast({ 
        title, 
        icon: 'none',
        duration: 3000 
      });
      return;
    }

    const openID = wx.getStorageSync('openID');
    const jwt_token = wx.getStorageSync('jwt_token');
    if (!openID || !jwt_token) {
      this.showToast({ title: '请先登录', icon: 'none', duration: 2000 });
      return;
    }

    const code = e.detail.code;
    if (!code) {
      this.showToast({ title: '获取授权码失败', icon: 'none', duration: 2000 });
      return;
    }

    this.setData({ isLoading: true });
 
    wx.request({
      url: `${baseUrl}/user/wechat/get-phone`,
      method: 'POST',
      data: { 
        openID, 
        code 
      },
      header: { 'Authorization': `Bearer ${jwt_token}` },
      success: (res) => {
        if (res.statusCode === 200 && res.data.mobile) {
          this.setData({ 'userInfo.mobile': res.data.mobile });
          this.showToast({ title: '手机号授权成功', duration: 2000 });
        } else {
          const errorMsg = res.data.detail || '获取手机号失败';
          console.error('后端返回错误:', res);
          let title = errorMsg;
          if (errorMsg.includes('短信验证')) {
            title = '请打开微信，在“我-设置-个人信息-手机号”中绑定手机号并完成短信验证';
          } else if (errorMsg.includes('额度不足') || errorMsg.includes('上限')) {
            title = '功能使用次数已达上限，请联系管理员';
          }
          this.showToast({ 
            title, 
            icon: 'none',
            duration: 4000 
          });
        }
      },
      fail: (err) => {
        console.error('手机号授权请求失败:', err);
        let failMsg = '网络错误，请稍后重试';
        if (err.data && err.data.detail) {
          failMsg = err.data.detail.includes('短信验证') 
            ? '请打开微信，在“我-设置-个人信息-手机号”中绑定手机号并完成短信验证' 
            : err.data.detail.includes('额度不足') || err.data.detail.includes('上限')
              ? '功能使用次数已达上限，请联系管理员'
              : err.data.detail;
        }
        this.showToast({ 
          title: failMsg, 
          icon: 'none',
          duration: 4000 
        });
      },
      complete: () => {
        this.setData({ isLoading: false });
      }
    });
  }
});